//
//  HttpService.swift
//  ParkManage
//
//  Created by cf on 2020/9/17.
//  Copyright © 2020 diligrp. All rights reserved.
//

import Foundation
import Moya

let isNetworkError = "networkError"

func getMultiTarget(_ target: TargetType) -> MultiTarget {
    return MultiTarget(target)
}

// 设置请求超时时间
let requestTimeoutClosure = { (endpoint: Endpoint, done: @escaping MoyaProvider<MultiTarget>.RequestResultClosure) in
    do {
        var request = try endpoint.urlRequest()
        request.timeoutInterval = 10.0
        done(.success(request))
    } catch {
        return
    }
}

private let provider = MoyaProvider<MultiTarget>(requestClosure: requestTimeoutClosure)

// 请求队列
var requestTasks: [Cancellable] = []

class HttpService {
    
    // 发起请求
    static func sendRequest(_ target: MultiTarget, completion: @escaping ((_ result: [String: Any]?, _ success: Bool) -> Void)) {
       let request = provider.request(target) { (result) in

            switch result {
            case let .success(response):
                do {
                    //print(response.request?.allHTTPHeaderFields)
                    let data = try response.mapJSON()
                    let jsonData = data as? [String: Any]
                    
                    if response.statusCode == 200 {
                        if jsonData?["code"] as? Int == 200 {
                            if jsonData?["data"] as? [String: Any] != nil {
                                completion(jsonData?["data"] as? [String: Any], true)
                            } else if jsonData?["result"] as? [String : Any] != nil {
                                completion(jsonData?["result"] as? [String: Any], true)
                            } else {
                                completion(jsonData, true)
                            }
                        } else {
            
                        }
                    } else {
                        completion(jsonData, false)
                    }
                } catch {
                    completion(["msg": response.codeErrorDescribe], false)
                }

            case let .failure(error):

                completion(["msg": error.localizedDescription, isNetworkError: true], false)
            }
        }
        // 请求队列
        requestTasks.append(request)
    }
    
    // 取消请求队列
    static func cancelRequest() {
        for task in requestTasks {
            task.cancel()
        }
        requestTasks.removeAll()
    }
    
    static func logout() {

    }
}
